package com.GPT.controller;

import com.GPT.common.Code;
import com.GPT.common.Result;
import com.GPT.common.UserId;
import com.GPT.domain.Newuser;
import com.GPT.domain.UserVo;
import com.GPT.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

import static com.GPT.common.EmailService.sendEmail;
import static com.GPT.common.ValidateCodeUtils.generateValidateCode;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private  RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     * @param newuser
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Newuser newuser){
        //邮箱校验，密码校验
        if (newuser.getEmail() == null || !Code.EMAIL_PATTERN.matcher(newuser.getEmail()).matches()) {
            return Result.error("邮箱格式不正确");
        }
        if (newuser.getPasswordHash() == null || newuser.getPasswordHash().length() < 6) {
            return Result.error("密码不能为空且长度必须大于六位");
        }

        Result login = userService.login(newuser);
        return login;
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        // 前端清除本地存储中的 JWT 令牌
        //localStorage.removeItem('token');
        return Result.msg("退出成功");
    }

    /**
     * 发送验证码
     * @param newuser
     * @return
     */
    @PostMapping("/email")
    public Result Email(@RequestBody Newuser newuser){
        //邮箱校验
        if (newuser.getEmail() == null || !Code.EMAIL_PATTERN.matcher(newuser.getEmail()).matches()) {
            return Result.error("邮箱格式不正确");
        }
        //如果redis存在，继续等待
        if (redisTemplate.opsForValue().get(newuser.getEmail())!=null){
            // 获取验证码的剩余有效时间
            Long remainingTime = redisTemplate.getExpire(newuser.getEmail(), TimeUnit.SECONDS);
            if (remainingTime != null) {
                // 返回剩余有效时间
                return Result.error(String.valueOf(remainingTime));
            }
        }
        //发送邮件
        String code=String.valueOf(generateValidateCode(4));
        try {
            sendEmail(newuser.getEmail(), code);
        }catch (Exception e){
            return Result.error("发送失败");
        }
        // 记录验证码code到 Redis 中，使用邮箱地址作为键，验证码作为值
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        // 设置过期时间为2分钟
        valueOperations.set(newuser.getEmail(), code, 2, TimeUnit.MINUTES);
        return Result.success(newuser.getEmail(),"验证码已发送");
    }

    /**
     * 注册
     * @param userVo
     * @return
     */
    @PostMapping("/register")
    public Result saveRegister(@RequestBody UserVo userVo){
        //邮箱校验，密码校验，验证码校验
        if (userVo.getEmail() == null || !Code.EMAIL_PATTERN.matcher(userVo.getEmail()).matches()) {
            return Result.error("邮箱格式不正确");
        }
        if (userVo.getPasswordHash() == null || userVo.getPasswordHash().length() < 6) {
            return Result.error("密码不能为空且长度必须大于六位");
        }
        if (userVo.getCode() == null || !userVo.getCode().matches("\\d{4}")) {
            return Result.error("验证码必须是四位数字");
        }
        Result result = userService.saveRegister(userVo);
        return result;
    }
    @PostMapping("/bindEmail")
    public Result bindEmail(HttpServletRequest request, @RequestBody UserVo userVo) {
        // Step 1: 验证用户是否已经存在
        LambdaQueryWrapper<Newuser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Newuser::getEmail, userVo.getEmail());
        Newuser existingUser = userService.getOne(queryWrapper);

        if (existingUser == null) {
            return Result.error("用户不存在，请先注册");
        }

        // Step 2: 验证密码是否正确
        String providedPassword = DigestUtils.md5DigestAsHex(userVo.getPasswordHash().getBytes());
        if (!existingUser.getPasswordHash().equals(providedPassword)) {
            return Result.error("密码错误");
        }

        if(existingUser.getOpenid()!= null){
            return Result.error("该邮箱已经绑定微信");
        }
        // Step 3: 绑定 openid 并更新数据库
        existingUser.setOpenid(userVo.getOpenid());
        existingUser.setNickname(userVo.getNickname());
        existingUser.setHeadimgurl(userVo.getHeadimgurl());
        boolean updateSuccess = userService.updateById(existingUser);

        if (updateSuccess) {
            return Result.success(existingUser, "绑定成功");
        } else {
            return Result.error("绑定失败，请稍后重试");
        }
    }
    @PostMapping("/checkOpenId")
    public Result checkOpenId(@RequestBody UserVo userVo) {
        // Step 1: 使用 openid 查询用户信息
        LambdaQueryWrapper<Newuser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Newuser::getOpenid, userVo.getOpenid());
        Newuser existingUser = userService.getOne(queryWrapper);

        // Step 2: 判断该 openid 是否存在
        if (existingUser != null) {
            // OpenID 存在，返回用户信息
            return Result.success(existingUser.getId(), "OpenID 存在");
        } else {
            // OpenID 不存在
            return Result.error("OpenID 不存在");
        }
    }
}
